var socketio = require('socket.io')
var io 
var guestNumber = 1
var nickNames = {}
var namesUsed = []
var currentRoom = {}


exports.listen = function(server){
    io = socketio.listen(server)  // 启动SocketIO服务器，允许它搭载在已有的HTTP服务器上，
    io.set('log level',1)
    io.sockets.on('connection',function(socket){  // 定义每个用户连接的处理逻辑
        guestNumber = assignGuestName(socket,guestNumber,nickNames,namesUsed) //在用户连接上来的时候赋予一个访客名
        joinRoom(socket,'Lobby')  //在用户连接上来的时候，默认lobby聊天室

        // 处理用户的消息，更名以及聊天室的创建和变更
        handleMessageBroadcasting(socket,nickNames)
        handleNameChangeAttempts(socket,nickNames,namesUsed)
        handleRoomJoining(socket)  

        // 用户发出请求时，向其提供已经被占用的聊天室列表
        socket.on('rooms',function(){
            socket.emit('rooms',io.sockets.manager.rooms)
        })

        // 用户断开连接的时候
        handleClientDisconnection(socket,nickNames,namesUsed)

    })

}


// 分配用户昵称
function assignGuestName(socket,guestNumber,nickNames,namesUsed){
    var name = 'Guest' + guestNumber
    nickNames[socket.id] = name
    socket.emit('nameResult',{
        success:true,
        name:name
    })
    namesUsed.push(name)
    return guestNumber + 1
}


// 进入聊天室
function joinRoom(socket,room){
    socket.join(room)  // 让用户进入房间
    currentRoom[socket.id] = room  // 记录用户的当前房间
    socket.emit('joinResult',{room:room})  // 让用户知道他们进入了新的房间

    // 让房间里的其他用户知道有新用户的进入了房间
    socket.broadcast.to(room).emit('message',{
        text:nickNames[socket.id] + 'has joined' + room + ': '
    })

    // 如果不止一个用户在这个房间里面，汇总下都是谁
    var usersInRoom = io.sockets.clients(room)
    if(usersInRoom.length > 1){
        var usersInRoomSummary = 'User currently in' + room + ':'
        for(var index in usersInRoom){
            var userSockedId = usersInRoom[index].id
            if(userSockedId != socket.id){
                if(index > 0){
                    usersInRoomSummary += ','
                }
                usersInRoomSummary +=nickNames[userSockedId]
            }
        }
        usersInRoomSummary += '.'
        socket.emit('message',{text:usersInRoomSummary})
    }
}


// 更名
function handleNameChangeAttempts(socket,nickNames,namesUsed){
    socket.on('nameAttempt',function(name){
        if(name.indexOf('Guest') == 0){
            socket.emit('nameResult',{
                success:false,
                message:'Names cannot begin with "Guest"'
            })
        }else{
            if(namesUsed.indexOf(name) == -1){
                var previousName = nickNames[socket.id]
                var previousNameIndex = namesUsed.indexOf(previousName)
                namesUsed.push(name)
                delete namesUsed[previousNameIndex]   // 删除以前用的用户名
                socket.emit('nameResult',{
                    success:true,
                    name:name
                })
                socket.broadcast.to(currentRoom[socket.id]).emit('message',{
                    text:previousName + 'is now known as ' + name + '.'
                })
            }else{
                socket.emit('nameResult',{
                    success:false,
                    message:'That name is already in use'
                })
            }
        }
    })
}


// 发送聊天消息
function handleMessageBroadcasting(socket){
    socket.on('message',function(message){
        socket.broadcast.to(message.room).emit('message',{
            text:nickNames[socket.id] + ':' +message.text
        })
    })
}


// 创建房间
function handleRoomJoining(socket){
    socket.on('join',function(room){
        socket.leave(currentRoom[socket.id])
        joinRoom(socket,room.newRoom)
    })
}


// 用户断开连接
function handleClientDisconnection(socket){
    socket.on('disconnect',function(){
        var nameIndex = namesUsed.indexOf(nickNames[socket.id])
        delete namesUsed[nameIndex]
        delete nickNames[socket.id]
    })
}